# -*- coding: utf-8 -*-
import json
import time
import logging

from common.transaction.model import Withdraw, WITHDRAW_STATUS
from common.utils import tz
from common.utils import tracker
from common.utils import exceptions as err
from common.utils.decorator import sql_wrapper

_LOGGER = logging.getLogger('alipay')


@sql_wrapper
def withdraw_success_action(pay_id, amount, trade_no, payer_no='group_new_withdraw'):
    item = Withdraw.query.with_for_update().filter(Withdraw.id == pay_id).filter(
        Withdraw.status == WITHDRAW_STATUS.SUBMIT_TO_THIRD).first()
    if item is None:
        _LOGGER.info('Auto trans alipay, withdraw_success_action is none %s' % str(pay_id))
        raise err.DataError('withdraw_success_action query fail')

    item.status = WITHDRAW_STATUS.DONE
    item.real_price = float(amount)
    trans_info = {}
    trans_info.update({
        'payer_no': payer_no,
        'code': '10000',
        'amount': amount,
        'order_id': trade_no,
        'out_biz_no': pay_id,
        'complete_pay_date': tz.local_now().strftime('%Y-%m-%d %H:%M:%S'),
    })
    updated_info = json.loads(item.extend)
    updated_info.update({'auto_trans_info': trans_info})
    item.extend = json.dumps(updated_info, ensure_ascii=False)
    item.save()
    tracker.track_withdraw(item.user_id, item.target_type, -float(amount))
    tracker.track_withdraw(item.user_id, item.target_type, float(amount), WITHDRAW_STATUS.DONE)
    return True


@sql_wrapper
def withdraw_failed_action(pay_id, amount, code, sub_code, sub_msg, out_biz_no,
    payer_no='group_new_withdraw'):
    item = Withdraw.query.with_for_update().filter(Withdraw.id == pay_id).filter(
        Withdraw.status == WITHDRAW_STATUS.SUBMIT_TO_THIRD).first()
    if item is None:
        _LOGGER.info('Auto trans alipay, withdraw_failed_action is none %s' % str(pay_id))
        raise err.DataError('withdraw_failed_action query fail')

    item.status = WITHDRAW_STATUS.FAIL
    trans_info = {}
    trans_info.update({
        'payer_no': payer_no,
        'amount': amount,
        'code': code,
        'sub_code': sub_code,
        'sub_msg': sub_msg,
        'out_biz_no': out_biz_no,
        'complete_pay_date': tz.local_now().strftime('%Y-%m-%d %H:%M:%S'),
    })
    updated_info = json.loads(item.extend)
    updated_info.update({'auto_trans_info': trans_info})
    item.extend = json.dumps(updated_info, ensure_ascii=False)
    item.save()
